package com.dtn.wsn.demo;

import com.dtn.wsn.httpsqs.Httpsqs4j;
import com.dtn.wsn.httpsqs.HttpsqsClient;
import com.dtn.wsn.httpsqs.HttpsqsException;
import com.dtn.wsn.middleware.HttpsqsMessageHandler;

/**
 * 
 * Client application for HTTPSQS to receive the request from php web
 * interface and return the response to the front-end web pages
 * 
 * @author hao
 */

public class HttpSqsReceiverThread extends Thread {
    
    private final String REQUEST_QUEUE = "java_php_request";
    private final String REPLY_QUEUE = "java_php_reply";
    private final String RETRY_QUEUE = "java_php_retry";
    private final String DEAD_QUEUE = "dead";
    //private final String RETRY_QUEUE = "java_php_request";
    
    private final String NACK = "NACK";
    private final String ACK = "ACK";
    
    public void run() {
        try {
            //establish the connection to HTTPSQS
            Httpsqs4j.setConnectionInfo("localhost", 1218, "UTF-8");
            System.out.println("httpsqs contection setup");
        } catch (HttpsqsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        HttpsqsClient client = Httpsqs4j.createNewClient();
        System.out.println("Listening on the port 1218 for receive queue");

        while (true) {
            String message;
            try {
                //get the message from the httpsqs
                message = client.getString(REQUEST_QUEUE).trim();
                System.out.println("get " + message);
                //handle request
                HttpsqsMessageHandler hmsgHandler = new HttpsqsMessageHandler();
                
                switch (hmsgHandler.handle(message)) {
                    case 0:
                        client.putString(REPLY_QUEUE, ACK);
                        break;
                    case 1:
                        client.putString(RETRY_QUEUE, message);
                        break;
                    case 2:
                        client.putString(DEAD_QUEUE, message);
                        break;
                }


            } catch (HttpsqsException e1) {
                try {
                    Thread.sleep(1000);
                    //System.out.println("rest");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                continue;
            }
        }



    }
}
